(function($){
    var client = new com.im.common.ajax();
    var tmpOrgType = [];//组织类型
    var loadList =  [];
    var loading = false;
    var TimeFn = null;
    var orgparam = {pageInfo :{pageSize:20,pageNumber :1}};
    var orgcolumns=[[
        {field:'orgId',title:"序号",width:40,fitColumns:true,
            formatter: function(value,row,index){
                return  '<input type="checkbox" name="com_unit_choose_r" class="minimal" value='+index+'></input>';
            }},
        {field:'orgName',title:"单位名称",width:100,fitColumns:true},
        {field:'orgCode',title:"单位编码",width:100,fitColumns:true},
        {field:'orgType',title:"单位类型",width:100,fitColumns:true,
            formatter: function(value,row,index){
                var orgTypeName = '未定义';
                $.each(tmpOrgType,function(i,obj){
                    if(obj.id == value){
                        orgTypeName = obj.text;
                        return false;
                    }
                });
                return orgTypeName ;
            }},
        {field:'orgAddr',title:"单位地址",width:100,fitColumns:true},
        {field:'orgTel',title:"联系方式",width:100,fitColumns:true},
        {field:'orgFax',title:"传真",width:100,fitColumns:true},
        {field:'orgEmail',title:"邮箱",width:100,fitColumns:true},
        {field:'linkMan',title:"联系人",width:100,fitColumns:true}
    ]];

    var methods = {
        init: function(options) {
            var o = $.extend({
                elmIdOrgTypeSel : "comp_org_type_sel",//条件输入--类型下拉
                elmIdOrgTypeTree : "comp_org_type_tree",//条件输入--组织树
                elmIdOrgNameInput : "comp_org_name_input",//需要展示的位置
                elmIdModal : "unitSearchModal",//需要展示的位置
                elmIdOut : "unitOut",//单击时回填的文本框
                hasOrgType : true,//是否先展示组织类型
                callbackFunc: function(orgId,orgName) {
                }
            }, options || {});

            var self = this;

            onInit(o.treeOnClick,o);

            return this;
        },
        treeOnClickInner : function(self,opt){
            //加载数据
            return o.treeOnClick('1','test');
        }

    };

    function onInit(func,opt) {
        //渲染查询界面
        _render(opt);

        //加载数据
        var param = {};
        if(opt.hasOrgType){
            //如果要展示组织类型
            param.hasOrgType = 'Y';
        }
        var result = client.callAsJson("userService/queryOrgarizationsByCond", param);
        if (result.success) {
            var list = result.result;
            tmpOrgType = list;
            //初始化组织类型下拉
            $("#"+opt.elmIdOrgTypeSel).append("<option value=''>全部</option>");
            $.each(list,function(i,obj){
                $("#"+opt.elmIdOrgTypeSel).append("<option value='"+obj.id+"'>"+obj.text+"</option>"); ;
            });
            $('.select2').select2();
            //初始化组织树
            $('#'+opt.elmIdOrgTypeTree).tree({
                data: list,
                onClick: function (node) {
                    //单击事件 选择
                    // 取消上次延时未执行的方法
                    clearTimeout(TimeFn);
                    //执行延时
                    TimeFn = setTimeout(function(){
                        //单击事件要执行的代码
                        _treeOnClick(node,func,opt);
                    },300);

                },
                onDblClick: function (node) {//双击事件 展开

                    clearTimeout(TimeFn);
                    _getOrgTree(node,func,opt);
                }
            });
        } else {
            toastr.error("服务器忙，稍后再试！" + result.resultMsg);
        }
    };

    function _getOrgTree(node,func,opt){
        if(loading){
            //加载中
            return false;
        }
        loading = true;
        //是否已经加载过
        var ifLoaded = false;
        $.each(loadList,function(i,obj){
            if(obj == node.id){
                ifLoaded = true;
                return false;
            }
        });
        //没加载过,且可加载
        if(!ifLoaded && node.state == 'closed'){
            var param = {};
            if(node.attributes.dataType == 'ORG_TYPE'){
                //如果是组织类型
                param.orgType = node.id;
            }else{
                param.parentOrgId = node.id;
            }
            var result = client.callAsJson("userService/queryOrgarizationsByCond", param);
            if (result.success) {
                //设置为已加载
                loadList.push(node.id);
                var list = result.result;
                $('#'+opt.elmIdOrgTypeTree).tree('append', {
                    parent: node.target,
                    data: list
                });
                //切换折叠状态
                $('#'+opt.elmIdOrgTypeTree).tree('toggle',  node.target);
            } else {
                toastr.error("服务器忙，稍后再试！" + result.resultMsg);
            }
        }else{
            //切换折叠状态
            $('#'+opt.elmIdOrgTypeTree).tree('toggle',  node.target);
        }
        loading = false;
    };
    //单机选择时
    function _treeOnClick(node,func,opt){
        if(node.attributes != undefined && node.attributes.dataType == 'ORG_TYPE'){
            //组织类型点击展示组织树
            _getOrgTree(node,func,opt);
            return false;
        }
        // if(opt.elmIdOut != null && opt.elmIdOut != undefined){
        //     $("#"+opt.elmIdOut).val(node.text);
        //     $("#"+opt.elmIdOut).attr("orgId",node.id);
        // }
        orgparam.orgId = node.id;
        orgparam.forOrgList = 'Y';
        orgparam.orgType = '';
        _queryOrgList(1);
        //return func(node.id,node.text);
    }

    function _render(opt){
        //获取模态框
        var modal = $("#"+opt.elmIdModal);
        //清空
        modal.empty();
        var pDiv = $($.parseHTML('  <div class="modal-dialog modal-lg myModal_lg" role="document">' +
            '    <div class="modal-content">' +
            '      <div class="modal-header">' +
            '        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
            '        <h4 class="modal-title">单位搜索</h4>' +
            '      </div>' +
            '      <div class="modal-body modalGrayBg">' +
            '        <!--内容开始-->' +
            '        <div class="box box-default">' +
            '          <div class="box-header with-border">' +
            '            <div class="row">' +
            '              <div class="col-md-12">' +
            '' +
            '                <div class="form-inline">' +
            '                  <div class="form-group">' +
            '                    <label>单位类型：</label>' +
            '                      <select id="comp_org_type_sel" class="form-control select2">' +
            '                      </select>' +
            '                  </div>' +
            '                  <div class="form-group">' +
            '                    <label>单位名称：</label>' +
            '                    <input id="comp_org_name_input" type="text" class="form-control" placeholder="请输入单位名称"/>' +
            '                  </div>' +
            '                  <button id="comp_org_search_btn" type="submit" class="btn btn-info"><i class="fa fa-search"></i> 查询</button>' +
            '                </div>' +
            '' +
            '              </div>' +
            '            </div>' +
            '          </div>' +
            '              <div class="box-body">' +
            '                <div class="col-sm-2 noLeftPadding">' +
            '                  <div class="treeMenu">' +
            '                    <ul id="comp_org_type_tree" class="easyui-tree">' +
            '                    </ul>' +
            '                  </div>' +
            '                </div>' +
            '                <div class="myTable">' +
            '                  <table id="comp_org_list_tab" class="table table-bordered table-striped">' +
            '                  </table>' +
             '                  <div class="myPage">' +
             '                    <div id="comp_org_page"></div>' +
             '                  </div>' +
            '                </div>' +
            '              </div>' +
            '        </div>' +
            '      <!--内容结束-->' +
            '      </div>' +
            '' +
            '      <div class="modal-footer">' +
            '        <button id="comp_org_close_btn" type="button" class="btn btn-default">关闭</button>' +
            '        <button id="comp_org_ensure_btn" type="button" class="btn btn-primary">确定</button>' +
            '      </div>' +
            '    </div>' +
            '  </div>'));
        modal.append(pDiv);
        $("#"+opt.elmIdModal).modal("show");
        //查询
        $('#comp_org_search_btn').click(function () {
            orgparam.forOrgList = 'Y';
            orgparam.orgType = $("#comp_org_type_sel").val();
            orgparam.orgName = $("#comp_org_name_input").val();
            orgparam.orgId = '';
            _queryOrgList(1);
        });
        //确认选择
        $("#comp_org_ensure_btn").click(function () {
            _returnFunc(opt);
        });
        //关闭
        $("#comp_org_close_btn").click(function () {
            $("#"+opt.elmIdModal).empty();
            $("#"+opt.elmIdModal).modal("hide");
        });
    };
    function _queryOrgList(pageNum){

        $("#comp_org_list_tab").empty();
        var pageInfo = {};
        pageInfo.pageNumber = pageNum;
        pageInfo.pageSize  = 20
        orgparam.pageInfo  = pageInfo;

        var result = client.callAsJson("userService/queryOrgarizationsByCondPage", orgparam);
        if (result.success) {
            if(result.result != null){
                $("#comp_org_list_tab").datagrid({
            	    nowrap:false,
            	    fitColumns:true,
                    columns : orgcolumns,
                    data : result.result,
                    onClickRow : function(idx){
            	        com.im.common.util.onClickRowCom({elmTable:"comp_org_list_tab",rowIndex:idx});
            	    }
                });
                //页码
                $("#comp_org_page").pagination({
                    total : result.result.total,
                    pageSize : result.result.pageSize,
                    pageNumber : result.result.pageNumber,
                    pageList : [20 , 40],
                    beforePageText:  '第' ,
                    afterPageText: '页 共'+result.result.totalPages+'页',
                    displayMsg: '共 '+result.result.total+'条记录',
                    onSelectPage: function (pageNumber, pageSize) {
                        orgparam.pageInfo.pageNumber = pageNumber;
                        orgparam.pageInfo.pageSize = pageSize;
                        _queryOrgList(pageNumber);
                    }
                });

                //设置radio事件，因为会执行onClickRow，所以radio单机事件处理为不做任何变化，避免冲突
                $("input[name=com_unit_choose_r]").click(function () {
                    var c = $(this).prop("checked");
                    if(c){
                        $(this).prop("checked",false);
                    }else{
                        $(this).prop("checked",true);
                    }
                });
            }
        } else {
            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        }

    };
    function _returnFunc(opt){
        var orgIdx = $("input[name='com_unit_choose_r']:checked").val();
        if(orgIdx != undefined){
            var org = $('#comp_org_list_tab').datagrid('getData').rows[orgIdx];
            if(opt.elmIdOut != null && opt.elmIdOut != undefined){
                $("#"+opt.elmIdOut).val(org.orgName);
                $("#"+opt.elmIdOut).attr("orgId",org.orgId);
            }
            //模态框清空，避免同一界面出现多个组织选择时，无法弹出
            $("#"+opt.elmIdModal).empty();
            $("#"+opt.elmIdModal).modal("hide");
            return opt.callbackFunc(org.orgId,org.orgName);
        }else{
            toastr.warning("您未选择任何组织单位!!");
        }
    };
    
    $.fn.unitSearchCommpent = function(method) {

        if (methods[method] && method.charAt(0) != '_') {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist on jQuery.pagination');
        }
    };

})(jQuery);